package pmr.view;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.eclipse.jdt.core.IMethod;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

public class RemoveUnusedDialog extends Dialog implements ICheckStateListener {

	private final Map<String, IMethod> unusedMethodsMap = new HashMap<String, IMethod>();
	private CheckboxTableViewer viewer;
	private final Set<IMethod> methodsToRemove = new HashSet<IMethod>();

	public RemoveUnusedDialog(Shell parentShell, Set<IMethod> unusedMethods) {
		super(parentShell);
		for (IMethod m : unusedMethods) {
			unusedMethodsMap.put(m.getElementName(), m);
		}
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite composite = (Composite) super.createDialogArea(parent);
		composite.setLayout(new FillLayout());
		viewer = CheckboxTableViewer.newCheckList(composite, SWT.BORDER);
		viewer.addCheckStateListener(this);
		for (String methodLabel : unusedMethodsMap.keySet()) {
			viewer.add(methodLabel);
		}
		return composite;
	}

	@Override
	public void create() {
		super.create();
		getButton(IDialogConstants.OK_ID).setEnabled(false);
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("Unused Methods");
	}

	@Override
	protected void okPressed() {
		for (Object ob : viewer.getCheckedElements()) {
			String s = (String) ob;
			methodsToRemove.add(unusedMethodsMap.get(s));
		}
		super.okPressed();
	}

	public Set<IMethod> getMethodsToRemove() {
		return methodsToRemove;
	}

	public void checkStateChanged(CheckStateChangedEvent event) {
		boolean buttonStatus = viewer.getCheckedElements().length == 0 ? false
				: true;
		getButton(IDialogConstants.OK_ID).setEnabled(buttonStatus);

	}

}
